#include "client.h"

Client::Client(Connection* connection, QObject *parent = 0) :
    QObject(parent)
{
    _connection = connection;
    this->connect(_connection,SIGNAL(connected()),SLOT(on_connection_connected()));
    this->connect(_connection,SIGNAL(disconnecting()),SLOT(on_connection_disconnecting()));
}

Client::Client(const Client &client) :
    QObject(client.parent())
{
    this->_connection = client.connection();
}

Client::~Client()
{
    this->disconnect();
}

Connection *Client::connection() const
{
    return _connection;
}

void Client::on_connection_connected()
{
    _connection->receiveLine();
}

void Client::on_connection_disconnecting()
{
    //TODO: Tester l'envoi de quit et la deconnection propre
    _connection->send(QString("QUIT\r\n"));
}

bool Client::getFile(const QString filename, const QString destinationFilename, FileState &filestate)
{
    if(send("GETF " % filename))
    {
        QString command = QString();
        quint32 size;
        QTextStream in(_connection->receiveLine().toAscii());
        in >> command;
        if(command == "SIZE")
        {
            in >> size;
            filestate = Exist;
            QFile* file = new QFile(destinationFilename);
            if(file->open(QFile::WriteOnly))
            {
                file->write(_connection->receive(size));
                file->close();
            }
        }
        else if(command == "BUSY")
            filestate = Busy;
        else if(command == "NONE")
            filestate = NotExist;
        return true;
    }
    else
        return false;
}

bool Client::getList(QStringList &list)
{
    if(send("LIST"))
    {
        QString command;
        forever
        {
           QTextStream in(_connection->receiveLine().toUtf8());
           in >> command;
           if(command != "ENDL")
               list.append(in.readLine());
           else
               break;
        }
        return true;
    }
    else
        return false;
}

bool Client::freeFile(const QString filename)
{
    return send("FREE" % filename);
}

bool Client::send(const QString command)
{
    _connection->send(command % "\r\n");
    return (_connection->receiveLine() == ("RCPT " % command  % "\r\n"));
    //TODO: Se reconnecter en cas de problème
}
